import * as base from "./base.js";
import instance from './request.js';
import { $, $$ } from './base.js';


window.addEventListener('load', function () {
    base.navbox();
    base.avatarimg();
    

    let detailid = 0;
    let wishid = localStorage.getItem('detailid');
    let wishbutarr = [];
    //心愿单
    //名称
    $('.wishcreate_m_t input').addEventListener('focus', function () {
        $('.wishcreate_m_name').style.transform = 'scale(0.8) translateX(-10px) translateY(-15px)';
        $('.wishcreate_m_t').style.border = '1px solid #222';
    })
    $('.wishcreate_m_t input').addEventListener('blur', function () {
        $('.wishcreate_m_t').style.border = '1px solid #b0b0b0';
        if (!($('.wishcreate_m_t input').value)) {
            $('.wishcreate_m_name').style.transform = 'scale(1) translateX(0px) translateY(0px)';
        }
    })


    //清除
    $('.wishcreate_b_l').addEventListener('click', function () {
        $('.wishcreate_m_t input').value = '';
    })


    //限制字数
    $('.wishcreate_m_t input').addEventListener('input', function () {
        const count = $('.wishcreate_m_t input').value.length;
        $('.min_num').textContent = count;

        if (count >= parseInt($('.max_num').textContent)) {
            // 如果超过最大字数限制，则截断输入
            $('.wishcreate_m_t input').value = $('.wishcreate_m_t input').value.slice(0, parseInt($('.max_num').textContent - 1));
        }
    });


    let closenum = 0;
    //关闭创建心愿单
    $('.w_close_c').addEventListener('click', function () {
        if (closenum == 1) {
            $('.wishcreate').style.display = 'none';
            $('.wishbox').style.display = 'block';
        } else {
            $('.wishmask').style.display = 'none';
            $('.wishcreate').style.display = 'none';
        }
    })

    $('.w_close').addEventListener('click', function () {
        $('.wishmask').style.display = 'none';
        $('.wishbox').style.display = 'none';
        closenum = 0;
    })


    $('.collect_button').addEventListener('click', function () {
        if (wishnum == 0) {
            $('.wishmask').style.display = 'block';
            $('.wishcreate').style.display = 'block';
        }

        if (wishnum == 1) {
            $('.wishbox').classList.add('slidedownup');
            if (localStorage.getItem('data-lazynum') == 1) {

                uniqueArr().then(result => {
                    let uniqueArray = result.uniqueArray;
                    let wisharr = result.wisharr;
                    let delarr = [];
                    // console.log(wisharr);

                    wisharr.forEach(function (value, index, array) {
                        let that = wisharr[index];
                        that.homes.forEach(function (value, index, array) {
                            if (wishid == that.homes[index].id) {
                                delarr.push(that.id);
                            }
                        });
                    });

                    console.log(delarr);
                    renewal();
                    wishbutarr = Array.from(new Set(delarr));
                    deltetew(Array.from(new Set(delarr)))
                }).catch(error => {
                    console.error(error);
                });


            } else {
                renewal();
                $('.wishmask').style.display = 'block';
                $('.wishbox').style.display = 'block';
                
            }
        }
    })





    let wishnum = 0;
    let shoucangarr = [];
    let uniqueArray = [];

    origin();
    function origin() {
        instance.get('/collection', {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            let wisharr = response.data.data;



            if (wisharr.length) {
                wishnum = 1;

                wisharr.forEach(function (value, index, array) {
                    let str = `<div class="wishbox_li">
                    <label for="${wisharr[index].id}">
                    <input type="checkbox" name="" id="${wisharr[index].id}" class="checkbox wish_checkbox">
                    <div class="wish_mask" id="${wisharr[index].id}"></div>
                       <div class="wishbox_li_t">
                           <div class="wishbox_li_tn">
                           </div>
                       </div>
                       <div class="wishbox_li_b">
                           <div class="wishbox_li_b_t">${wisharr[index].name}</div>
                           <div class="wishbox_li_b_b"><span>${wisharr[index].count}</span>心愿单项目</div>
                       </div>
                       </label>
                       </div>`

                    $('.wishbox_m_body').insertAdjacentHTML('beforeend', str);
                    // $('.wishcreate_ul').insertAdjacentHTML('beforeend', str);
                    let that = wisharr[index];

                    that.homes.forEach(function (value, index, array) {
                        shoucangarr.push(that.homes[index].id);
                    })
                })
            }

            uniqueArray = Array.from(new Set(shoucangarr));


            checkfun();

        })
    }



    //获取被收藏的房源
    function uniqueArr() {
        return new Promise((resolve, reject) => {
            instance.get('/collection', {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {
                let wisharr = response.data.data;

                let shoucangarr = [];

                if (wisharr.length) {
                    wisharr.forEach(function (value, index, array) {
                        let that = wisharr[index];

                        that.homes.forEach(function (value, index, array) {
                            shoucangarr.push(that.homes[index].id);
                        });
                    });
                }

                let uniqueArray1 = Array.from(new Set(shoucangarr));
                uniqueArray = Array.from(new Set(shoucangarr));


                resolve({ uniqueArray: uniqueArray1, wisharr: wisharr }); // 返回结果
            }).catch(error => {
                reject(error); // 返回错误
            });
        });
    }




    //移出收藏
    function deltetew(delarr) {
        let checkarr = [];


        // 获取所有的复选框元素
        const checkboxes = $$('.wishbox_li input[type="checkbox"]');

        // 获取全选复选框元素
        const toggleCheckbox = $('.allcheck input');

        checkboxes.forEach(function (checkbox, index1) {
            delarr.forEach(function (value, index, array) {
                console.log(checkboxes[index1].id == value);
                if (checkboxes[index1].id == value) {
                    checkbox.checked = true;
                    checkarr.push(checkboxes[index1].id);
                }
            })
        });


        let allChecked = true;
        checkboxes.forEach(function (checkbox) {
            if (!checkbox.checked) {
                allChecked = false;
            }
        });

        // 更新全选复选框的选中状态
        toggleCheckbox.checked = allChecked;

        $('.wishmask').style.display = 'block';
        $('.wishbox').style.display = 'block';


    }






    //控制多选框
    function allCheckboxes(obj1, obj2) {
        // 获取所有的复选框元素
        const checkboxes = $$(`${obj2} input[type="checkbox"]`);

        // 获取全选复选框元素
        const toggleCheckbox = $(`${obj1} input`);

        // 获取全选复选框的选中状态
        const isChecked = toggleCheckbox.checked;

        // 遍历所有复选框元素，并设置它们的选中状态与全选复选框一致
        checkboxes.forEach(function (checkbox) {
            checkbox.checked = isChecked;
        });
    }
    function updateCheckbox(obj1, obj2) {
        // 获取所有的复选框元素
        const checkboxes = $$(`${obj2} input[type="checkbox"]`);

        // 获取全选复选框元素
        const toggleCheckbox = $(`${obj1} input`);

        // 检查是否所有复选框都被选中
        let allChecked = true;
        checkboxes.forEach(function (checkbox) {
            if (!checkbox.checked) {
                allChecked = false;
            }
        });

        // 更新全选复选框的选中状态
        toggleCheckbox.checked = allChecked;
    }

    //收藏的
    function checkfun() {
        $('.allcheck input').addEventListener('click', function () {
            allCheckboxes('.allcheck', '.wishbox_li');
        })
        $$('.wishbox_li input[type="checkbox"]').forEach(function (value, index, array) {
            $$('.wishbox_li input[type="checkbox"]')[index].addEventListener('click', function () {
                updateCheckbox('.allcheck', '.wishbox_li');
            })
        })
    }





    //收藏的"完成"
    $('.wishbox_b_com').addEventListener('click', base.debounce(function (event) {
        wishbut();
    })
    );


    function wishbut() {
        console.log(wishbutarr);
        let shouyes = 0;
        let shouno = 0;
        const requestConfigs = [];
        const unrequestConfigs = [];


        $$('.wishbox_li input[type="checkbox"]').forEach(function (checkbox, index) {
            if (!(checkbox.checked) && wishbutarr.includes(parseInt($$('.wishbox_li input[type="checkbox"]')[index].id))) {
                shouyes = 1;

                const requestConfig = {
                    url: `/collection/home`,
                    method: 'DELETE',
                    data: {
                        collectionId: $$('.wishbox_li input[type="checkbox"]')[index].id,
                        homeId: wishid
                    },
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                };

                console.log(checkbox);
                checkbox.parentNode.children[3].children[1].children[0].innerHTML--;

                requestConfigs.push(requestConfig);
            }
            if (checkbox.checked && !(wishbutarr.includes(parseInt($$('.wishbox_li input[type="checkbox"]')[index].id)))) {
                shouno = 1;

                const unrequestConfig = {
                    url: `/collection/home`,
                    method: 'POST',
                    data: {
                        collectionId: $$('.wishbox_li input[type="checkbox"]')[index].id,
                        homeId: wishid
                    },
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                };

                console.log(checkbox);
                checkbox.parentNode.children[3].children[1].children[0].innerHTML++;

                unrequestConfigs.push(unrequestConfig);

            }
        })

        if (shouyes == 1) {
            wishbutpromise(requestConfigs);
            shouyes = 0;
        }
        if (shouno == 1) {
            wishbutpromise(unrequestConfigs);
            shouno = 0;
        }


    }



    function wishbutpromise(requestConfigs) {

        // 创建包含所有请求的 Promise 数组
        const promises = requestConfigs.map(requestConfig => instance(requestConfig));

        // 使用 Promise.all 等待所有请求完成
        Promise.all(promises)
            .then(function (responses) {
                // 处理每个请求的响应
                responses.forEach(function (response, index) {
                    console.log(`Response ${index + 1}:`, response.data);
                });



                renewal();

                //重新获取一次收藏的房源
                // uniqueArr();


                $('.wishmask').style.display = 'none';
                $('.wishbox').style.display = 'none';
            }).then(response => {
                uniqueArr().then(result => {
                    let uniqueArray = result.uniqueArray;
                    if (!(uniqueArray.includes(parseInt(wishid)))) {
                        $('.collect_but_no').style.display = 'block';
                        $('.collect_but_yes').style.display = 'none';
                        $('.collect_span').innerHTML = '收藏';
                        localStorage.setItem('data-lazynum', 0);
                    } else {
                        $('.collect_but_yes').style.display = 'block';
                        $('.collect_but_no').style.display = 'none';
                        $('.collect_span').innerHTML = '已收藏';
                        localStorage.setItem('data-lazynum', 1);
                    }

                }).catch(error => {
                    console.error(error);
                });
            })
            .catch(function (error) {
                // 处理错误
                console.error('Error:', error);
            });
    }

    //更新多选框
    function renewal() {
        const checkboxes = $$('.wishbox_li input[type="checkbox"]');

        checkboxes.forEach(function (checkbox) {
            checkbox.checked = false;
        });
        $('.allcheck input').checked = false;
    }



    //创建心愿单
    function wishcreate() {
        if ($('.wishcreate_m_t input').value) {
            instance.post('/collection', {
                name: $('.wishcreate_m_t input').value
            }, {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {
                console.log(response);
                let wisharr = response.data.data;
                $('.wishcreate_m_t input').value = '';
                $('.wishmask').style.display = 'none';
                $('.wishcreate').style.display = 'none';

                let str = `<div class="wishbox_li">
                <label for="${wisharr.id}">
                <input type="checkbox" name="" id="${wisharr.id}" class="checkbox wish_checkbox">
                <div class="wish_mask" id="${wisharr.id}"></div>
                   <div class="wishbox_li_t">
                       <div class="wishbox_li_tn">
                       </div>
                   </div>
                   <div class="wishbox_li_b">
                       <div class="wishbox_li_b_t">${wisharr.name}</div>
                       <div class="wishbox_li_b_b"><span>0</span>心愿单项目</div>
                   </div>
                   </label>
                   </div>`

                $('.wishbox_m_body').insertAdjacentHTML('beforeend', str);

                uniqueArr();
                checkfun();

                if (wishnum == 0) {
                    origin();
                }

            }).catch(error => {
                console.error(error)
            })
        }
    }


    //创建心愿单
    $('.wishcreate_b_r').addEventListener('click', base.debounce(function () {
        wishcreate();
    }))
    $('.wishbox_b_box').addEventListener('click', function () {
        $('.wishbox').style.display = 'none';
        $('.wishcreate').style.display = 'block';
        closenum = 1;
    })


})